<template>
  <!-- 规则管理 -->
  <el-row>
    <el-col :span="5">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick"
              :filter-node-method="filterNodeMethod" />
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="19">
      <basic-container>
        <avue-crud :option="option" :search.sync="search" :table-loading="loading" :data="data" ref="crud" v-model="form"
          :permission="permissionList" @row-del="rowDel" @row-update="rowUpdate" @row-save="rowSave"
          :before-open="beforeOpen" :page.sync="page" @search-change="searchChange" @search-reset="searchReset"
          @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
          @refresh-change="refreshChange" @on-load="onLoad">
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">添加
            </el-button>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button type="text" size="small" icon="el-icon-view" @click.stop="handleDetail(scope.row)">详情
            </el-button>
            <el-button type="text" size="small" icon="el-icon-edit" @click.stop="handleUpdate(scope.row)">编辑
            </el-button>
            <el-button type="text" size="small" icon="el-icon-video-play" @click.stop="handleDebug(scope.row)">调试
            </el-button>
          </template>
        </avue-crud>

      </basic-container>
    </el-col>
  </el-row>
</template>

<script>
import { getList, getDetail, add, update, remove } from "@/api/system/ruleManage";
import { getTenantTree } from "@/api/base/pictureAlgorithm";

import { mapGetters } from "vuex";
import website from "@/config/website";

export default {
  data() {
    return {
      treeDeptId: '',
      treeData: [],
      treeOption: {
        nodeKey: 'id',
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentId = (node.level === 0) ? 0 : node.data.id;
          getTenantTree(parentId).then(res => {
            resolve(res.data.data.map(item => {
              return {
                ...item,
                leaf: !item.hasChildren
              }
            }))
          });
        },
        addBtn: false,
        menu: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'tenantName',
          value: 'id',
          children: 'children'
        }
      },
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        selection: false,
        refreshBtn: false,
        columnBtn: false,
        searchShowBtn: false,
        dialogClickModal: false,
        // dialogFullscreen:true,
        menuWidth:300,
        column: [
          {
            label: "规则名称",
            prop: "ruleName",
            search: true,
          },
          {
            label: "规则类型",
            prop: "status",
            hide: true,
            type: "select",
            dicUrl: '/api/blade-platform/rule/ruleType',
            // search: true,
            rules: [{
              required: true,
              message: "请选择",
              trigger: "blur"
            }]
          },
          {
            label: "成立阈值",
            prop: "scope",
          },
          {
            label: "异常原因",
            prop: "abnormalCause",
          },
          {
            label: "说明",
            prop: "ruleDescribe",
          },
          {
            label: '创建时间',
            prop: 'createTime',
            type: 'datetime',
            addDisplay: false,
            // search: true,
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
          },
        ],
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.post_add, false),
        // viewBtn: this.vaildData(this.permission.post_view, false),
        // delBtn: this.vaildData(this.permission.post_delete, false),
        // editBtn: this.vaildData(this.permission.post_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    // 非租户模式默认加载管理组数据
    if (!website.tenantMode) {
      this.initData(website.tenantId);
    }
  },

  methods: {
    handleAdd(row) {
      // if (this.treeDeptId == '') {
      //   this.$message({
      //     type: "warning",
      //     message: "请选择需要添加规则的医院！！！"
      //   });
      //   return;
      // }
      this.$router.push({
        path: '/ruleManage/add',
      })
    },
    handleDetail(row) {
      this.$router.push({
        path: '/ruleManage/detail',
        query: {
          id: row.id,
        },
      })
    },
    handleUpdate(row) {
      this.$router.push({
        path: '/ruleManage/edit',
        query: {
          id: row.id,
        },
      })
    },
    handleDebug(row) {
      this.$router.push({
        path: '/ruleManage/debug',
        query: {
          id: row.id,
        },
      })
    },
    initData(tenantId) {
      // getTenantTree(tenantId).then(res => {
      //   const column = this.findObject(this.option.group, "roleId");
      //   column.dicData = res.data.data;
      // });
      // getDeptTree(tenantId).then(res => {
      //   const column = this.findObject(this.option.group, "deptId");
      //   column.dicData = res.data.data;
      // });
      // getPostList(tenantId).then(res => {
      //   const column = this.findObject(this.option.group, "postId");
      //   column.dicData = res.data.data;
      // });
    },
    filterNodeMethod(value, data) {
      if (!value) return true;
      return data.tenantName.indexOf(value) !== -1;
    },
    nodeClick(data) {
      this.treeDeptId = data.tenantId;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    rowSave(row, done, loading) {
      const item = {
        ...row,
        tenantId: this.treeDeptId
      }
      add(item).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {

      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query, {
        tenantId: this.treeDeptId
      })).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style></style>
